﻿using System.Net;
using System.Text;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;
using UtilZ.Dotnet.Ex.Communication.Net.Udp;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.Ex.Model;

namespace WinFormApp
{
    public partial class FUdpClient : Form
    {
        public FUdpClient()
        {
            InitializeComponent();
        }


        private NetUdpClient _udpClient = null;
        private IPEndPoint _remoteEndPoint = null;

        private void FUdpClient_Load(object sender, EventArgs e)
        {
            try
            {
                var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
                if (redirectAppenderToUI != null)
                {
                    redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
                }

                var unpacker = new TestNetUdpListenerUnpacker();
                unpacker.PackOutput += Unpacker_PackOutput;
                var initPara = new NetUdpClientInitPara(unpacker, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5002));
                //initPara.ReceiveDataMode = ReceiveDataMode.Sync;
                initPara.ReceiveDataMode = ThreadMode.Async;
                this._udpClient = new NetUdpClient(initPara);
                this._udpClient.Start();

                this._remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5001);
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }

        private void Unpacker_PackOutput(object sender, DataOutputArgs e)
        {
            string text = Encoding.UTF8.GetString(e.Data.Bytes, 0, e.Data.Bytes.Length);
            Loger.Info($"收到数据:{text}");
        }


        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            logControl.AddLog(e.Item.Content, e.Item.Level);
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            logControl.Clear();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes($"夜风yf~!@#:{TimeEx.GetTimestamp()}");
                //this._udpClient.Send(buffer, this._remoteEndPoint);
                this._udpClient.SendToAsync(this._remoteEndPoint, buffer);
                Loger.Info("发送成功");
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }
    }


    internal class TestNetUdpListenerUnpacker : UnpackerAbs
    {
        protected override int PrimitiveUnPackge(IUnpackerPara unpackerPara)
        {
            var netPara = (NetUdpUnpackerPara)unpackerPara;
            base.OnRaiseOnReceivedData(netPara.Client, new DataOutputArgs(netPara.LinkInfo, new DataSource(netPara.Buffer, 0, netPara.DataLength)));
            return netPara.DataLength;
        }
    }
}
